<?php
/**
 * 定时计算红包分成
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

$db = new MysqliDb (Array(
    'host' => MYSQLDB,
    'username' => MYSQLDB_USER,
    'password' => MYSQLDB_PWD,
    'db' => MYSQLDB_DATABASE,
    'port' => 3306,
    'prefix' => 'au_',
    'charset' => 'utf8'));


$conf = $db->where('name', 'DIRECT_PACKET_DEAL')->getValue('setting', 'value');
$conf = json_decode($conf, true);
$rate = $conf['rate'];
//从redis中取出数据
$redis = new Redis();
$redis->connect(REDIS_HOST, REDIS_PORT);

while (true) {
    $ret = $redis->lPop("packet_list");
    if ($ret === false) {
        logUtil("No data,sleep 300 s", "INFO");
        sleep(300);
        continue;
    }
    $log = json_decode($ret, true);
    if (!is_array($log)) {
        logUtil("数据格式错误", "ERROR");
        continue;
    }
    $broker = getBrokerInfoByAid($log['aid']);
    if (empty($broker)) {
        logUtil($log['aid'] . " 经纪人不存在", "ERROR");
        continue;
    }
//    //判断有无上级
//    if ($broker['superior_id'] < 1) {
//        //没有上级直接全给他
//        $insert_id = addCommissionLog($log['rp_id'], $log['aid'], $log['other_aid'], $log['type'], $log['amount'], $log['create_time']);
//        if ($insert_id < 1) {
//            divide_log($log['rp_id'], $log['aid'], $log['other_aid'], $log['amount'], 2);
//        }
//        divide_log($log['rp_id'], $log['aid'], $log['other_aid'], $log['amount'], 1);
//    } else {
//        //添加本人的直接交易记录
//        $insert_id = addCommissionLog($log['rp_id'], $log['aid'], $log['other_aid'], $log['type'], $log['amount'] * $rate, $log['create_time']);
//        if ($insert_id < 1) {
//            divide_log($log['rp_id'], $log['aid'], $log['other_aid'], $log['amount'], 2);
//            return;
//        }
//        divide_log($log['rp_id'], $log['aid'], $log['other_aid'], $log['amount'], 1);
    $yu = $log['amount'] * (1 - $rate);
    divide($log['rp_id'], $broker['superior_id'], $log['aid'], $yu, 3, $log['create_time']);
//    }
}

//经纪人分成
function divide($rp_id, $aid, $other_aid, $yu, $type, $create_time)
{
    global $rate;
    $broker = getBrokerInfoByAid($aid);
    //计算上级金额,判断<1,不往下分,末端得 没有上级,全部获得
    if ($yu < 1 || $broker['superior_id'] < 1) {
        $insert_id = addCommissionLog($rp_id, $aid, $other_aid, $type, $yu, $create_time);
        if ($insert_id < 1) {
            divide_log($rp_id, $aid, $other_aid, $yu, 2);
        }
        divide_log($rp_id, $aid, $other_aid, $yu, 1);
        return;
    }
    $amount = $yu * $rate;
    $insert_id = addCommissionLog($rp_id, $aid, $other_aid, $type, $amount, $create_time);
    if ($insert_id < 1) {
        divide_log($rp_id, $aid, $other_aid, $amount, 2);
        return;
    }
    divide_log($rp_id, $aid, $other_aid, $amount, 1);
    $yu = $yu - $amount;
    //递归
    divide($rp_id, $broker['superior_id'], $aid, $yu, 3, $create_time);
}

//获取经纪人信息
function getBrokerInfoByAid($aid)
{
    global $db;
    if ($aid < 1) {
        return false;
    }
    $broker = $db->where('aid', $aid)->getOne('agent');
    return $broker;
}

//添加记录
function addCommissionLog($rp_id, $aid, $other_aid, $type, $amount, $create_time)
{
    global $db;
    $broker = getBrokerInfoByAid($aid);
    $date = date("Y-m-d", strtotime($create_time));
    $data = [
        'rp_id' => $rp_id,
        'aid' => $aid,
        'other_aid' => $other_aid,
        'commission_type' => $type,
        'amount' => $amount,
        'type' => 1,
        'create_time' => $create_time
    ];
    //开启事务
    $db->startTransaction();
    $id = $db->insert('commission_log', $data);
    if (!$id)
        $db->rollback();

    //更新经纪人数据,total_money,wallet
    $ret = $db->where('aid', $aid)->update('agent', [
        'total_money' => $db->inc($amount),
        'wallet' => $db->inc($amount)
    ]);
    if (!$ret)
        $db->rollback();

    //经纪人每日收益
    $ret = $db->onDuplicate(['total_money'], 'id')->insert('personal_daily_income', [
        'aid' => $aid,
        'superior_id' => $broker['superior_id'],
        'date' => $date,
        'total_money' => $db->inc($amount)
    ]);
    if (!$ret)
        $db->rollback();

    //我属于团队
    if ($broker['superior_id'] > 0) {
        //添加团队每日收益
        $ret = $db->onDuplicate(['total_money'], 'id')->insert('team_daily_income', [
            'tid' => $broker['superior_id'],
            'date' => $date,
            'total_money' => $db->inc($amount),
        ]);
        if (!$ret)
            $db->rollback();
        //团队累积的金额
        $ret = $db->where('tid', $broker['superior_id'])->update('agent_team', [
            'total_money' => $db->inc($amount),
        ]);
        if (!$ret)
            $db->rollback();
    }

    //我的团队
    $my_team = $db->where('tid', $aid)->getOne('agent_team');
    if (!empty($my_team)) {
        //添加团队每日收益
        $ret = $db->onDuplicate(['total_money'], 'id')->insert('team_daily_income', [
            'tid' => $aid,
            'date' => $date,
            'total_money' => $db->inc($amount),
        ]);
        if (!$ret)
            $db->rollback();
        //团队累积的金额
        $ret6 = $db->where('tid', $aid)->update('agent_team', [
            'total_money' => $db->inc($amount),
        ]);
        if (!$ret)
            $db->rollback();
    }
    $db->commit();
    return $id;
}

//记录分成失败和成功的日志
function divide_log($rp_id, $aid, $other_aid, $amount, $type = 1)
{
    if ($type == 1) {
        $log_level = "INFO";
        $result = "Success";
    } else {
        $log_level = "ERROR";
        $result = "Failure";
    }
    logUtil("[ $result ],red packet: $rp_id, broker: $aid, other: $other_aid, amount: $amount", $log_level);
}
